
const ArticleModel = require('@/dbModels/articleModel');


async function articleCreate(payload) {
    const article = new ArticleModel(payload);
    await article.save();
    return article;
}


async function articleQuery(payload) {
  const { page, pageSize } = payload;
  //const query = { title: new RegExp(title, 'i') }; // 创建一个正则表达式来实现模糊查询
  const skip = (page - 1) * pageSize; // 计算需要跳过的文档数量
  const total = await ArticleModel.countDocuments();
  const articles = await ArticleModel.find()
    .sort({ created_at: -1 }) // 执行查询
    .populate('author')
    .skip(skip) // 跳过前面的文档
    .limit(pageSize) // 限制返回的文档数量

  return {articles,total}
}



async function articleUpdate(payload) {
    const { _id, updatedFields } = payload
    const result = await ArticleModel.updateOne({ _id: _id }, updatedFields )
    return result;
}


async function articleDelete(payload) {
    const { id } = payload
    const result = await ArticleModel.deleteOne({ _id: id });
    return result;
}


module.exports = { 
    articleCreate,
    articleQuery,
    articleUpdate,
    articleDelete
};




